import pymysql

from ..config_util import mysql_config


class ListPageMysqlConnectUtil(object):
    def __enter__(self):
        select_sql = "SELECT region, url FROM regional_table_of_delicacies;"
        insert_sql = "INSERT INTO list_page(detail_describe, label, detail_url, region) " \
                     "VALUES ({detail_describe!r}, {label!r}, {detail_url!r}, {region!r})"
        create_sql = """
                    CREATE TABLE
                    IF
                        NOT EXISTS `dp`.`list_page` (
                        `id` BIGINT ( 20 ) NOT NULL AUTO_INCREMENT COMMENT '主键自增',
                        `detail_url` VARCHAR ( 1000 ) NOT NULL COMMENT '详情页url',
                        `detail_describe` VARCHAR ( 100 ) NOT NULL COMMENT '详情描述（最佳排行或分类最佳）',
                        `label` VARCHAR ( 100 ) NOT NULL COMMENT '细分标签',
                        `region` VARCHAR ( 100 ) NOT NULL COMMENT '所属地区',
                        `update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                        PRIMARY KEY ( `id` ),
                        UNIQUE KEY ( `detail_url` ) 
                        ) ENGINE = INNODB CHARACTER 
                        SET = UTF8 COMMENT '详情页url';
                    """

        self.connection = pymysql.connect(**mysql_config)
        self.cursor = self.connection.cursor()
        try:
            self.cursor.execute(create_sql)
            self.connection.commit()
        except Exception as e:
            self.connection.rollback()
            raise Exception(str(e))
        return self.connection, self.cursor, select_sql, insert_sql

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cursor.close()
        self.connection.close()
